//81MHz/4 count 20250 times is 1ms
AT_RAM
void X_TunePll(u16 u16Trim)
{
    u32 pll_con1,pll_con1_temp1,pll_con1_temp2;

    local_irq_disable();

    pll_con1 = JL_PLL->CON1;
    pll_con1_temp1 = (pll_con1&0x00000FFF) + 2;

    pll_con1_temp2 = (pll_con1_temp1*20250)/u16Trim - 2;
    //if (((pll_con1_temp1*20250)%u16Trim) > 10125) pll_con1_temp2 = pll_con1_temp2 + 1;

    pll_con1 = (pll_con1&0xFFFFF000)|pll_con1_temp2;
    JL_PLL->CON1 = pll_con1;

    udelay(100);

    local_irq_enable();
}
void X_UsbCalibrateClk()
{
    u8 i;
    u16 u16Timer1Cap0,u16Timer1Cap1;

    //select input channel
    INPUT_CHANNLE1_SRC_SEL(USB_DM_INT_IO);
    gpio_set_direction(USB_DM_INT_IO, 1);
    gpio_set_die(USB_DM_INT_IO, 1);
	IRFLT_OUTPUT_TIMER_SEL(IRFLT_OS_TIMER1);

    JL_IRFLT->CON = 0;  //clear
    JL_IRFLT->CON = (IRFLT_PSEL_1 | IRFLT_TSRC_SYS | IRFLT_EN_EN);		//irflt config


    //filter 5 times 1ms KA
    JL_TMR1->CON = BIT(6);  //clear interrupt
    JL_TMR1->PRD = 0;
    JL_TMR1->CNT = 0;
    JL_TMR1->CON = (TIMER1_PSET_DIV4 | TIMER1_SSEL_LSB | TIMER1_MODE_FALL);  //div4 + lsb + falling edge

    for (i=0;i<5;i++)
    {
         while(!(JL_TMR1->CON & BIT(7)));//wait PND
        JL_TMR1->CON |= BIT(6);
        u16Timer1Cap0 = JL_TMR1->PRD;
        while(!(JL_TMR1->CON & BIT(7)));//wait PND
        JL_TMR1->CON |= BIT(6);
        u16Timer1Cap1 = JL_TMR1->PRD;
    }

    //USB KA
    while(!(JL_TMR1->CON & BIT(7)));//wait PND
    JL_TMR1->CON |= BIT(6);
    u16Timer1Cap0 = JL_TMR1->PRD;
    while(!(JL_TMR1->CON & BIT(7)));//wait PND
    JL_TMR1->CON = BIT(6);//stop Timer1 capture
    u16Timer1Cap1 = JL_TMR1->PRD;

    log_info("KA time: %d",u16Timer1Cap1-u16Timer1Cap0);

    X_TunePll(u16Timer1Cap1-u16Timer1Cap0);

    //test USB KA after tune pll
    JL_TMR1->CON = BIT(6);  //clear interrupt
    JL_TMR1->PRD = 0;
    JL_TMR1->CNT = 0;
    JL_TMR1->CON = (TIMER1_PSET_DIV4 | TIMER1_SSEL_LSB | TIMER1_MODE_FALL);  //div4 + lsb + falling edge

    while(!(JL_TMR1->CON & BIT(7)));//wait PND
    JL_TMR1->CON |= BIT(6);
    u16Timer1Cap0 = JL_TMR1->PRD;
    while(!(JL_TMR1->CON & BIT(7)));//wait PND
    JL_TMR1->CON = BIT(6);//stop Timer1 capture
    u16Timer1Cap1 = JL_TMR1->PRD;

    log_info("KA time after trimming: %d",u16Timer1Cap1-u16Timer1Cap0);
    ////////////////////////////////////////////////////////////////////
}